/**
 * Project Name:shiro-progress
 * File Name:RetryLimitHashedCredentialsMatcher.java
 * Package Name:com.pango.shiroprogress.credentials
 * Date:May 15, 201410:44:47 AM
 * Copyright (c) 2014, fuqiongsong@gmail.com All Rights Reserved.
 *
*/

package com.pango.core.security.shiro.credentials;

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

/**
 * ClassName:RetryLimitHashedCredentialsMatcher <br/>
 * Date:     May 15, 2014 10:44:47 AM <br/>
 * @author   thierry.fu
 * @version  
 * @since    JDK 1.6
 * @see 	 
 */
public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {

    private Cache<String, AtomicInteger> passwordRetryCache;

    public RetryLimitHashedCredentialsMatcher(CacheManager cacheManager) {
        passwordRetryCache = cacheManager.getCache("passwordRetryCache");
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        String username = (String)token.getPrincipal();
        AtomicInteger retryCount = passwordRetryCache.get(username);
        if(retryCount == null) {
            retryCount = new AtomicInteger(0);
            passwordRetryCache.put(username, retryCount);
        }
        boolean matches = super.doCredentialsMatch(token, info);
        
        if(matches) {
        	
            passwordRetryCache.remove(username);
        }else {
        	
            if(retryCount.incrementAndGet() > 5) {
            	/**
            	 * 5次执行之后抛出错误;
            	 */
                throw new ExcessiveAttemptsException();
            }
        }
        return matches;
    }
}
